package io.afu.dnspod.actions;

import com.alibaba.fastjson.JSON;
import io.afu.dnspod.constant.Common;
import io.afu.dnspod.dto.RecordResp;
import io.afu.dnspod.dto.UpdateRecordResp;
import io.afu.httprequest.HttpRequest;

import java.util.HashMap;
import java.util.Map;

public class DRecord {

    public static RecordResp getRecordList(String tokenid,String token,String format,String domainid,String subdomain){
        Map<String,Object> params = makeCommonParams(tokenid,token,format,domainid);
        if (subdomain != null){
            params.put("sub_domain",subdomain);
        }
        String result = HttpRequest.getInstance().setParams(params).setUrl("https://dnsapi.cn/Record.List").useFormData().post();
        RecordResp recordResp = JSON.parseObject(result,RecordResp.class);
        System.out.println(result);
        System.out.println(recordResp.getRecords().get(0).getName());
        return recordResp;
    }

    /**
     * 形成公共的参数
     * @param tokenid tokenid
     * @param token token
     * @param format 格式
     * @param domainid 域名id
     * @return 参数map
     */
    private static Map<String,Object> makeCommonParams(String tokenid,String token,String format,String domainid){
        String loginToken = tokenid+","+token;
        Map<String,Object> params = new HashMap<>();
        params.put("login_token",loginToken);
        params.put("format",format);
        params.put("domain_id",domainid);
        return params;
    }

    public static Boolean updateRecord(String tokenid,String token,String format,String domainid,String subdomain,String recordid,String newrecord){
        Map<String,Object> params = makeCommonParams(tokenid,token,format,domainid);
        params.put("record_id",recordid);
        params.put("sub_domain",subdomain);
        params.put("record_type","A");
        params.put("record_line","默认");
        params.put("value",newrecord);
        String result = HttpRequest.getInstance().setParams(params).setUrl("https://dnsapi.cn/Record.Modify").useFormData().post();
        UpdateRecordResp updateRecordResp = JSON.parseObject(result,UpdateRecordResp.class);
        return updateRecordResp.getStatus().getCode().equals(Common.SUCCESS);
    }


}
